import {
  useCallback,
  useEffect,
  useRef,
} from 'react'
import { useMemoizedFn } from './use-memoized-fn'
import { isNumber } from '@/library/tool-kits/is-valid'

export type UseTimeout = (fn: () => void, delay?: number) => () => void;

/**
 * @description setTimeout计时器函数hook
 * @param fn {() => void} - 待执行函数
 * @param delay {undefined | number} - 定时时间（单位为毫秒）,支持动态变化，当取值为 undefined 时会停止计时器
 * @returns {() => void} 清理定时器函数
 */
export const useTimeout: UseTimeout = (fn: () => void, delay = 0) => {
  const timerCallback = useMemoizedFn(fn)
  const timerRef = useRef<number | null>(null)

  const clear = useCallback(() => {
    if (timerRef.current) {
      clearTimeout(timerRef.current)
    }
  }, [])

  useEffect(() => {
    if (!isNumber(delay) || delay < 0) {
      return
    }
    timerRef.current = window.setTimeout(timerCallback, delay)
    return clear
  }, [delay])

  return clear
}
